package com.lvmama.pangolin.util;

import com.lvmama.pangolin.common.Constant;
import com.lvmama.pangolin.common.StringTools;
import com.lvmama.pangolin.conf.ConfigManager;
import com.lvmama.pangolin.entity.TicketProductGrade;
import com.lvmama.pangolin.entity.lmm.LMMTicketCommodity;
import com.lvmama.pangolin.entity.mt.MTTicketCommodityItem;
import com.lvmama.pangolin.entity.qnr.QNRTicketCommodityItem;
import com.lvmama.pangolin.entity.tc.TCommodityItem;
import com.lvmama.pangolin.entity.tn.TNTicketCommodityItem;
import com.lvmama.pangolin.entity.xc.XCTicketCommodityItem;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommodityGradeUtil {
	/**
	 * @author zhoutianqi
	 * @className CommodityGradeUtil.java
	 * @date 2017年7月10日 下午1:38:11
	 * @description
	 */
	private static Logger logger = Logger.getLogger(CommodityGradeUtil.class);
	/**
	 * mianVal的值越大，得到的分数越高
	 * @param mainVal
	 * @param subList
	 * @return
	 */
	public static double compareValues1(String mainVal, String... subList) {
		double result = 0;
		for (String sbuVal : subList) {
			// 没有价格，不做比较
			if (StringTools.isValid(sbuVal)) {
				result += CommodityGradeUtil.compareValues1(Double.parseDouble(mainVal), Double.parseDouble(sbuVal));
			}
		}
		return result;
	}

	/**
	 * mianVal的值越大，得到的分数越高
	 * @param mainVal
	 * @param subVal
	 * @return
	 */
	public static double compareValues1(double mainVal, double subVal) {
		if (mainVal > subVal) {
			return Constant.EXCELLENT_SCORES;
		} else if (mainVal == subVal) {
			return Constant.EQUAL_SCORES;
		} else {
			return Constant.BAD_SCORES;
		}
	}

	/**
	 * mainVal值越大，得到的分数越低
	 * @param mainVal
	 * @param subList
	 * @return
	 */
	public static double compareValues2(String mainVal, String... subList) {
		double result = 0;
		for (String subVal : subList) {
			// 没有价格，不做比较
			if (StringTools.isValid(subVal)) {
				result += CommodityGradeUtil.compareValues2(Double.parseDouble(mainVal), Double.parseDouble(subVal));
			}
		}
		return result;
	}

	/**
	 * mainVal值越大，得到的分数越低
	 * @param mainVal
	 * @param subVal
	 * @return
	 */
	public static double compareValues2(double mainVal, double subVal) {
		if (mainVal > subVal) {
			return Constant.BAD_SCORES;
		} else if (mainVal == subVal) {
			return Constant.EQUAL_SCORES;
		} else {
			return Constant.EXCELLENT_SCORES;
		}
	}
	
	public static double getSKUGrade(int mainCommodityNum, int... commNumList) {
		double result = 0;
		int count = commNumList.length;
		for (int commNum : commNumList) {
			result += CommodityGradeUtil.compareValues1(mainCommodityNum, commNum);
		}

		return result / count;
	}

	public static double getTotalGrade(ConfigManager configManager, double commodityGrade, double skuGrade) {
		double commodityGradeWeight = Double.parseDouble(configManager
				.getParamValue(Constant.TICKET_PRODUCT_GRADE_PARAM_HANDEL, Constant.TICKET_COMMODITYGRADE_WEIGHT));
		double commodityNumWeight = Double.parseDouble(configManager
				.getParamValue(Constant.TICKET_PRODUCT_GRADE_PARAM_HANDEL, Constant.TICKET_COMMODITYNUM_WEIGHT));

		return commodityGrade * commodityGradeWeight + skuGrade * commodityNumWeight;
	}

	public static double getCommodityGrade(ConfigManager configManager, TicketProductGrade tpg) {
		return getObjectGrade(configManager, 1, tpg.getPriceGrade(), tpg.getRefundCondGrade(),
				tpg.getPreferentialGrade(), tpg.getEfficientGrade(), tpg.getBooktimeGrade());
	}

	// 处理退改数据
	public static double handelRefund(ConfigManager configManager, String refund) {
		// 退改字段为空，按照“条件退”处理
		if (!StringTools.isValid(refund)) {
			return 1;
		}
		// 随时退
		String[] strArray1 = configManager
				.getParamValue(Constant.TICKET_COMMODITY_REFUND_SITUATION, Constant.TICKET_REFUND_ANYTIME).split(";");
		for (String str1 : strArray1) {
			if (refund.contains(str1)) {
				return 2;
			}
		}
		// 条件退
		String[] strArray2 = configManager
				.getParamValue(Constant.TICKET_COMMODITY_REFUND_SITUATION, Constant.TICKET_REFUND_SOMETIME).split(";");
		for (String str2 : strArray2) {
			if (refund.contains(str2)) {
				return 1;
			}
		}
		return 0;
	}

	// 处理预定时间数据
	public static double handelBooktime(ConfigManager configManager, String booktime) {
		// 预定时间字段为空，按照“随时可订”处理
		if (StringUtils.isEmpty(booktime)) {
			return 0;
		}
		
		int day = 0,hour = 0, mins = 0;
		Date baseTime = new Date();
		
		try {
			baseTime = getBaseTime();
		} catch (Exception e) {
			logger.info("商品评分-获取日期异常"+e.getMessage());
		}
		
		// 提前一天预订
		String[] strArray2 = configManager
				.getParamValue(Constant.TICKET_COMMODITY_BOOKTIME_SITUATION, Constant.TICKET_BOOKTIME_BEFOREONEDAY).split(";");
		for (String str2 : strArray2) {
			if (booktime.equals(str2)) {
				booktime = "提前1天可预订";
				break;
			}
		}
		
		// 处理包含HH：MM类型的数据
		String regex = "\\d{1,2}:\\d{1,2}";
		Pattern p2 = Pattern.compile(regex);
		Matcher m2 = p2.matcher(booktime);
		if (m2.find()) {
			String[] hm = m2.group().split(":");
			hour = Integer.valueOf(hm[0]);
			mins = Integer.valueOf(hm[1]);
		}
		booktime = booktime.replaceAll(regex, "");
		
		// 提取字符串中“天”之前的数字，获取提前预定天数
		int dayIndex = booktime.indexOf("天");
		String dayStr = regex(booktime,dayIndex);
		if(StringUtils.isNotEmpty(dayStr)){
			day = Integer.valueOf(dayStr);
		}
		
		// 提取字符串中“点”之前的数字，获取提前预定小时数
		int hourIndex = booktime.indexOf("点");
		String hourStr = regex(booktime, hourIndex);
		if(StringUtils.isNotEmpty(hourStr)){
			hour = Integer.valueOf(hourStr);
		}
		
		// 提取字符串中“分”之前的数字，获取提前预定分钟数
		int minutesIndex = booktime.indexOf("分");
		String minsStr = regex(booktime, minutesIndex);
		if(StringUtils.isNotEmpty(minsStr)){
			mins = Integer.valueOf(minsStr);
		}
		
		if (day == 0 && hour == 0 && mins == 0)
			return 0;

		Date currTime = getCurrTime(day, hour, mins);
		long base = baseTime.getTime();
		long curr = currTime.getTime();
		// 返回相差分钟数
		return new BigDecimal((double)(base - curr)/(1000*60)).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
	}
	
	private static String regex(String booktime, int index) {
		String regex = "\\D*(\\d+)$";
		if (index != -1) {
			String subStr = booktime.substring(0, index);
			Pattern p1 = Pattern.compile(regex);
			Matcher m1 = p1.matcher(subStr);
			if (m1.find()) {
				return m1.group(1);
			}
		}
		return null;
	}

	/**  
     * 获得基准时间 ，下一天的零点整
     * 格式：2017-10-24 00:00:00  
     * @return Date  
     */  
	private static Date getBaseTime() throws Exception {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(DateUtils.addDays(new Date(), 1));
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		return calendar.getTime();
	}
	
	private static Date getCurrTime(int day, int hour, int mins){
		
		Calendar calendar = Calendar.getInstance();
		Date date = DateUtils.addDays(new Date(), -day);
		calendar.setTime(date);
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MINUTE, mins);
		calendar.set(Calendar.SECOND, 0);
		return calendar.getTime();
		
	}
	
	// 处理优惠力度数据
	public static double handelPreferential(ConfigManager configManager, String preferential) {
		String[] strArray1 = configManager
				.getParamValue(Constant.TICKET_COMMODITY_PREFERENTIAL_SITUATION, Constant.TICKET_PREFERENTIAL_SITUATION)
				.split(";");
		if (!StringTools.isValid(preferential)) {
			return 0;
		}
		if (preferential.contains(Constant.DOLLAR)) {
			return Double.parseDouble(preferential.split(Constant.DOLLAR)[1]);
		}
		for (String str : strArray1) {
			if (preferential.contains(str)) {
				return Double.parseDouble(preferential.split(str)[1].split(Constant.RENMINBI)[0]);
			}
		}
		return 0;
	}

	/**
	 * 根据多维度权重计算产品总得分
	 */
	public static double getObjectGrade(ConfigManager configManager, int size, double priceValue, double refundValue,
			double preferentialValue, double efficientValue, double booktimeValue) {
		double douSize = Double.parseDouble(String.valueOf(size));
		double priceWeight = Double.parseDouble(configManager
				.getParamValue(Constant.TICKET_COMMODITY_GRADE_PARAM_HANDEL, Constant.TICKET_PRICE_WEIGHT));
		double refundWeight = Double.parseDouble(configManager
				.getParamValue(Constant.TICKET_COMMODITY_GRADE_PARAM_HANDEL, Constant.TICKET_REFUND_WEIGHT));
		double preferentialWeight = Double.parseDouble(configManager
				.getParamValue(Constant.TICKET_COMMODITY_GRADE_PARAM_HANDEL, Constant.TICKET_PREFERENTIAL_WEIGHT));
		double efficientWeight = Double.parseDouble(configManager
				.getParamValue(Constant.TICKET_COMMODITY_GRADE_PARAM_HANDEL, Constant.TICKET_EFFICIENT_WEIGHT));
		double booktimeWeight = Double.parseDouble(configManager
				.getParamValue(Constant.TICKET_COMMODITY_GRADE_PARAM_HANDEL, Constant.TICKET_BOOKTIME_WEIGHT));
		return (priceValue * priceWeight + refundValue * refundWeight + preferentialValue * preferentialWeight
				+ efficientValue * efficientWeight + booktimeValue * booktimeWeight) / douSize;
	}

	public static double getProductGrade(ConfigManager configManager, double commodityGrade, int commodityNum,
			double pics, String score, String company) {
		double commodityGradeWeight = Double.parseDouble(configManager
				.getParamValue(Constant.TICKET_PRODUCT_GRADE_PARAM_HANDEL, Constant.TICKET_COMMODITYGRADE_WEIGHT));
		double commodityNumWeight = Double.parseDouble(configManager
				.getParamValue(Constant.TICKET_PRODUCT_GRADE_PARAM_HANDEL, Constant.TICKET_COMMODITYNUM_WEIGHT));
		/*double picsWeight = Double.parseDouble(configManager.getParamValue(Constant.TICKET_PRODUCT_GRADE_PARAM_HANDEL,
				Constant.TICKET_PICTURENUM_WEIGHT));
		double scoreWeight = Double.parseDouble(
				configManager.getParamValue(Constant.TICKET_PRODUCT_GRADE_PARAM_HANDEL, Constant.TICKET_SCORE_WEIGHT));*/
		//double doubleScore = handelScore(score, company);
		return (commodityGrade * commodityGradeWeight + commodityNum * commodityNumWeight);
				/*+ pics * picsWeight
				+ doubleScore * scoreWeight);*/
	}

	public static double handelScore(String score, String company) {
		// return 80 when the value is empty or null
		if (!StringTools.isValid(score)) {
			return 80;
		}
		if(score.contains("分")||score.contains("%")){
			score = score.substring(0, score.length() - 1).trim();
		}
		if (company.equals("TC")) {
			return Double.parseDouble(score);
		} else if (company.equals("TN")) {
			return Double.parseDouble(score);
		} else if (company.equals("XC")) {
			return Double.parseDouble(score) * 100 / 5;
		} else if (company.equals("QNR")) {
			return Double.parseDouble(score) * 100 / 5;
		}else if (company.equals("MT")) {
			return Double.parseDouble(score) * 100 / 5;
		}
		return Double.parseDouble(score) * 100 / 5;
	}
	
	/**
	 * 驴妈妈与携程对比后  携程报表
	 */
	public static void xcTicketProductGrade(TicketProductGrade lmmXcTpg, TicketProductGrade xcTpg, LMMTicketCommodity lmmComm,
			XCTicketCommodityItem xcComm) {
		 //驴妈妈产品跟竞品分别两两比较，都会产生与驴妈妈对应的报表，所以分开统计
		try {
			lmmXcTpg.setPriceGrade(lmmXcTpg.getPriceGrade()+compareValues2(lmmComm.getSalePrice(),xcComm.getSale_price()));
			lmmXcTpg.setBooktimeGrade(lmmXcTpg.getBooktimeGrade()+compareValues2(lmmComm.getBooktimeValue(),xcComm.getBooktimeValue()));
			lmmXcTpg.setEfficientGrade(lmmXcTpg.getEfficientGrade()+compareValues2(lmmComm.getEfficientValue(),xcComm.getEfficientValue()));
			lmmXcTpg.setRefundCondGrade(lmmXcTpg.getRefundCondGrade()+compareValues1(lmmComm.getRefundCondValue(),xcComm.getRefundCondValue()));
			lmmXcTpg.setPreferentialGrade(lmmXcTpg.getPreferentialGrade()+compareValues1(lmmComm.getPreferentialValue(),xcComm.getPreferentialValue()));
			lmmXcTpg.setCommodityNum(lmmXcTpg.getCommodityNum()+1);
			
			xcTpg.setPriceGrade(xcTpg.getPriceGrade()+compareValues2(xcComm.getSale_price(),lmmComm.getSalePrice()));
			xcTpg.setBooktimeGrade(xcTpg.getBooktimeGrade()+compareValues2(xcComm.getBooktimeValue(),lmmComm.getBooktimeValue()));
			xcTpg.setEfficientGrade(xcTpg.getEfficientGrade()+compareValues2(xcComm.getEfficientValue(),lmmComm.getEfficientValue()));
			xcTpg.setRefundCondGrade(xcTpg.getRefundCondGrade()+compareValues1(xcComm.getRefundCondValue(),lmmComm.getRefundCondValue()));
			xcTpg.setPreferentialGrade(xcTpg.getPreferentialGrade()+compareValues1(xcComm.getPreferentialValue(),lmmComm.getPreferentialValue()));
			xcTpg.setCommodityNum(xcTpg.getCommodityNum()+1);
		} catch (Exception e) {
			logger.info("产品评分-累加商品维度得分异常"+e.getMessage());
		}
	}

	public static void tcTicketProductGrade(TicketProductGrade lmmTcTpg, TicketProductGrade tcTpg, LMMTicketCommodity lmmComm,
			TCommodityItem tcComm) {
		try {
			lmmTcTpg.setPriceGrade(lmmTcTpg.getPriceGrade()+compareValues2(lmmComm.getSalePrice(),tcComm.getSale_price()));
			lmmTcTpg.setBooktimeGrade(lmmTcTpg.getBooktimeGrade()+compareValues2(lmmComm.getBooktimeValue(),tcComm.getBooktimeValue()));
			lmmTcTpg.setEfficientGrade(lmmTcTpg.getEfficientGrade()+compareValues2(lmmComm.getEfficientValue(),tcComm.getEfficientValue()));
			lmmTcTpg.setRefundCondGrade(lmmTcTpg.getRefundCondGrade()+compareValues1(lmmComm.getRefundCondValue(),tcComm.getRefundCondValue()));
			lmmTcTpg.setPreferentialGrade(lmmTcTpg.getPreferentialGrade()+compareValues1(lmmComm.getPreferentialValue(),tcComm.getPreferentialValue()));
			lmmTcTpg.setCommodityNum(lmmTcTpg.getCommodityNum()+1);
			
			tcTpg.setPriceGrade(tcTpg.getPriceGrade()+compareValues2(tcComm.getSale_price(),lmmComm.getSalePrice()));
			tcTpg.setBooktimeGrade(tcTpg.getBooktimeGrade()+compareValues2(tcComm.getBooktimeValue(),lmmComm.getBooktimeValue()));
			tcTpg.setEfficientGrade(tcTpg.getEfficientGrade()+compareValues2(tcComm.getEfficientValue(),lmmComm.getEfficientValue()));
			tcTpg.setRefundCondGrade(tcTpg.getRefundCondGrade()+compareValues1(tcComm.getRefundCondValue(),lmmComm.getRefundCondValue()));
			tcTpg.setPreferentialGrade(tcTpg.getPreferentialGrade()+compareValues1(tcComm.getPreferentialValue(),lmmComm.getPreferentialValue()));
			tcTpg.setCommodityNum(tcTpg.getCommodityNum()+1);
		} catch (Exception e) {
			logger.info("产品评分-累加商品维度得分异常"+e.getMessage());
		}
	}

	public static void tnTicketProductGrade(TicketProductGrade lmmTnTpg, TicketProductGrade tnTpg, LMMTicketCommodity lmmComm,
			TNTicketCommodityItem tnComm) {
		try {
			lmmTnTpg.setPriceGrade(lmmTnTpg.getPriceGrade()+compareValues2(lmmComm.getSalePrice(),tnComm.getSale_price()));
			lmmTnTpg.setBooktimeGrade(lmmTnTpg.getBooktimeGrade()+compareValues2(lmmComm.getBooktimeValue(),tnComm.getBooktimeValue()));
			lmmTnTpg.setEfficientGrade(lmmTnTpg.getEfficientGrade()+compareValues2(lmmComm.getEfficientValue(),tnComm.getEfficientValue()));
			lmmTnTpg.setRefundCondGrade(lmmTnTpg.getRefundCondGrade()+compareValues1(lmmComm.getRefundCondValue(),tnComm.getRefundCondValue()));
			lmmTnTpg.setPreferentialGrade(lmmTnTpg.getPreferentialGrade()+compareValues1(lmmComm.getPreferentialValue(),tnComm.getPreferentialValue()));
			lmmTnTpg.setCommodityNum(lmmTnTpg.getCommodityNum()+1);
			
			tnTpg.setPriceGrade(tnTpg.getPriceGrade()+compareValues2(tnComm.getSale_price(),lmmComm.getSalePrice()));
			tnTpg.setBooktimeGrade(tnTpg.getBooktimeGrade()+compareValues2(tnComm.getBooktimeValue(),lmmComm.getBooktimeValue()));
			tnTpg.setEfficientGrade(tnTpg.getEfficientGrade()+compareValues2(tnComm.getEfficientValue(),lmmComm.getEfficientValue()));
			tnTpg.setRefundCondGrade(tnTpg.getRefundCondGrade()+compareValues1(tnComm.getRefundCondValue(),lmmComm.getRefundCondValue()));
			tnTpg.setPreferentialGrade(tnTpg.getPreferentialGrade()+compareValues1(tnComm.getPreferentialValue(),lmmComm.getPreferentialValue()));
			tnTpg.setCommodityNum(tnTpg.getCommodityNum()+1);
		} catch (Exception e) {
			logger.info("产品评分-累加商品维度得分异常"+e.getMessage());
		}
	}

	public static void qnrTicketProductGrade(TicketProductGrade lmmQnrTpg, TicketProductGrade qnrTpg, LMMTicketCommodity lmmComm,
			QNRTicketCommodityItem qnrComm) {
		try {
			lmmQnrTpg.setPriceGrade(lmmQnrTpg.getPriceGrade()+compareValues2(lmmComm.getSalePrice(),qnrComm.getSale_price()));
			lmmQnrTpg.setBooktimeGrade(lmmQnrTpg.getBooktimeGrade()+compareValues2(lmmComm.getBooktimeValue(),qnrComm.getBooktimeValue()));
			lmmQnrTpg.setEfficientGrade(lmmQnrTpg.getEfficientGrade()+compareValues2(lmmComm.getEfficientValue(),qnrComm.getEfficientValue()));
			lmmQnrTpg.setRefundCondGrade(lmmQnrTpg.getRefundCondGrade()+compareValues1(lmmComm.getRefundCondValue(),qnrComm.getRefundCondValue()));
			lmmQnrTpg.setPreferentialGrade(lmmQnrTpg.getPreferentialGrade()+compareValues1(lmmComm.getPreferentialValue(),qnrComm.getPreferentialValue()));
			lmmQnrTpg.setCommodityNum(lmmQnrTpg.getCommodityNum()+1);
			
			qnrTpg.setPriceGrade(qnrTpg.getPriceGrade()+compareValues2(qnrComm.getSale_price(),lmmComm.getSalePrice()));
			qnrTpg.setBooktimeGrade(qnrTpg.getBooktimeGrade()+compareValues2(qnrComm.getBooktimeValue(),lmmComm.getBooktimeValue()));
			qnrTpg.setEfficientGrade(qnrTpg.getEfficientGrade()+compareValues2(qnrComm.getEfficientValue(),lmmComm.getEfficientValue()));
			qnrTpg.setRefundCondGrade(qnrTpg.getRefundCondGrade()+compareValues1(qnrComm.getRefundCondValue(),lmmComm.getRefundCondValue()));
			qnrTpg.setPreferentialGrade(qnrTpg.getPreferentialGrade()+compareValues1(qnrComm.getPreferentialValue(),lmmComm.getPreferentialValue()));
			qnrTpg.setCommodityNum(qnrTpg.getCommodityNum()+1);
		} catch (Exception e) {
			logger.info("产品评分-累加商品维度得分异常"+e.getMessage());
		}
	}
	public static void mtTicketProductGrade(TicketProductGrade lmmMtTpg, TicketProductGrade mtTpg, LMMTicketCommodity lmmComm,
			MTTicketCommodityItem mtComm) {
		try {
			lmmMtTpg.setPriceGrade(lmmMtTpg.getPriceGrade()+compareValues2(lmmComm.getSalePrice(),mtComm.getSale_price()));
			lmmMtTpg.setBooktimeGrade(lmmMtTpg.getBooktimeGrade()+compareValues2(lmmComm.getBooktimeValue(),mtComm.getBooktimeValue()));
			lmmMtTpg.setEfficientGrade(lmmMtTpg.getEfficientGrade()+compareValues2(lmmComm.getEfficientValue(),mtComm.getEfficientValue()));
			lmmMtTpg.setRefundCondGrade(lmmMtTpg.getRefundCondGrade()+compareValues1(lmmComm.getRefundCondValue(),mtComm.getRefundCondValue()));
			lmmMtTpg.setPreferentialGrade(lmmMtTpg.getPreferentialGrade()+compareValues1(lmmComm.getPreferentialValue(),mtComm.getPreferentialValue()));
			lmmMtTpg.setCommodityNum(lmmMtTpg.getCommodityNum()+1);

			mtTpg.setPriceGrade(mtTpg.getPriceGrade()+compareValues2(mtComm.getSale_price(),lmmComm.getSalePrice()));
			mtTpg.setBooktimeGrade(mtTpg.getBooktimeGrade()+compareValues2(mtComm.getBooktimeValue(),lmmComm.getBooktimeValue()));
			mtTpg.setEfficientGrade(mtTpg.getEfficientGrade()+compareValues2(mtComm.getEfficientValue(),lmmComm.getEfficientValue()));
			mtTpg.setRefundCondGrade(mtTpg.getRefundCondGrade()+compareValues1(mtComm.getRefundCondValue(),lmmComm.getRefundCondValue()));
			mtTpg.setPreferentialGrade(mtTpg.getPreferentialGrade()+compareValues1(mtComm.getPreferentialValue(),lmmComm.getPreferentialValue()));
			mtTpg.setCommodityNum(mtTpg.getCommodityNum()+1);
		} catch (Exception e) {
			logger.info("产品评分-累加商品维度得分异常"+e.getMessage());
		}
	}

}
